package com.gdziarmaga.webshop.web.managedBeans.client;

import java.io.IOException;
import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletException;

import org.springframework.beans.factory.annotation.Autowired;

import com.gdziarmaga.webshop.client.model.Client;
import com.gdziarmaga.webshop.client.services.ClientManager;
import com.gdziarmaga.webshop.utils.springcontext.AppContext;
import com.gdziarmaga.webshop.web.utils.FacesUtils;

@SessionScoped
@ManagedBean(name = "clientLoginBean")
public class ClientLoginBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3335815676096621193L;

	@Autowired
	private ClientManager clientManager;

	private boolean logged;

	private Client client;

	public Client getClient() {
		return client;
	}

	public void setClient(Client client) {
		this.client = client;
	}

	@PostConstruct
	public void init() {
		clientManager = (ClientManager) AppContext.getApplicationContext()
				.getBean("clientManager");
		logged = false;
		checkAdmin=false;
	}

	private boolean checkAdmin;
	

	private String login;

	private String password;

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String login() {
		client = clientManager.getClientByEmail(getLogin());
		String pass = client.getPasswd();

		if (getPassword().equals(pass)) {
			logged = true;
		} else {
			logged = false;
		}
		if(client.getEmail().equals("admin@wp.pl")){
			checkAdmin=true;
		}
		
		return null;

	}

	public boolean isCheckAdmin() {
		return checkAdmin;
	}

	public void setCheckAdmin(boolean checkAdmin) {
		this.checkAdmin = checkAdmin;
	}

	public void logout() {
		client = null;
		logged = false;
		((BasketBean) FacesUtils.getRequest().getSession()
				.getAttribute("basketBean")).getBook_list().clear();
		
		checkAdmin=false;
	}

	public void setLogged(boolean logged) {
		this.logged = logged;
	}

	public boolean isLogged() {
		return logged;
	}

	public void toConfirmAddressPage(ActionEvent event)
			throws ServletException, IOException {
		FacesUtils.redirect("/faces/mainContent/confirmAddressPage.xhtml");
	}

}
